/**
 * Created by douxin on 24/09/2016.
 */

import React from 'react';
import moment from 'moment';
import _ from 'lodash';
import NavBar from './NavBar';
import HomeContainer from './HomeContainer';
import MerchantProfileContainer from './MerchantProfileContainer';
import { httpRequest } from './YZApi';
import apiUrl from './ApiUrl';

class DashboardContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            menus: [{
                id: 1,
                name: '实时',
                position: 'left'
            }, {
                id: 3,
                name: '店铺',
                position: 'right'
            }, {
                id: 4,
                name: moment().format('YYYY-MM-DD'),
                position: 'right'
            }],
            selectedMenu: 1,
            merchant: {
                name: '实时交易大屏'
            },
            trades: [],
            fetched: false,
            pushMsgType: 'NoMsg', // NoMsg: 没有消息；NewTradeMsg: 新订单；PaymentMsg: 支付消息
            pushTradeIndex: -1
        };
        this.push = AV.push({
            appId: '9pabkCGS2s9khS3oUk35lfem-gzGzoHsz',
            appKey: 'kyf9j1lDG548DSD4qGXkO0kT'
        });
    }

    findTradeIndex(data) {
        return _.findIndex(this.state.trades, (t) => {
            return t.tid === data.tid;
        });
    }

    onPushMsgReceive(data) {
        const index = this.findTradeIndex(data);
        if (index >= 0) {
            // 订单已存在
            const leftVals = this.state.trades.slice(0, index);
            const rightVals = this.state.trades.slice(index + 1, this.state.trades.length);
            this.setState({
                trades: _.concat(leftVals, data, rightVals),
                fetched: true,
                pushMsgType: 'PaymentMsg',
                pushTradeIndex: index
            });
        } else {
            // 新订单
            this.setState({
                trades: _.concat(data, this.state.trades),
                fetched: true,
                pushMsgType: 'NewTradeMsg',
                pushTradeIndex: 0
            });
        }
    }

    componentDidMount() {
        const now = moment();
        const startDate = _.cloneDeep(now);
        const endDate = now.add(1, 'days');
        Promise.all([
            httpRequest(apiUrl.merchant.profile),
            httpRequest(`${apiUrl.trades.list}?startDate=${startDate.format('YYYY-MM-DD')}&endDate=${endDate.format('YYYY-MM-DD')}`)
            // httpRequest(`${apiUrl.trades.list}?startDate=2016-08-01&endDate=2016-09-26`)
        ]).then(data => {
            this.setState({
                merchant: data[0] || '实时交易大屏',
                trades: data[1]['trades'] || [],
                fetched: true
            });
        }).catch(err => {
            console.log(err);
        });

        const pushObj = this.push.open(() => {
            console.log('websocket opened');
        });

        httpRequest(`${apiUrl.merchant.installationId}?installationId=${pushObj['installationId']}`).then(result => {
            console.log('set merchant installation id success', result);
        }).catch(err => {
            console.log(err);
        });

        pushObj.on('message', (trade) => {
            console.log('receive push msg:', trade);
            this.onPushMsgReceive(trade.trade);
        });
    }

    handleMenuClick(index) {
        this.setState({
            selectedMenu: index
        });
    }

    renderHomeContent() {
        return (
            <HomeContainer trades={this.state.trades}
                           merchant={this.state.merchant}
                           pushMsgType={this.state.pushMsgType}
                           pushTradeIndex={this.state.pushTradeIndex}/>
        )
    }

    renderMerchantProfileContent() {
        return (
            <MerchantProfileContainer merchant={this.state.merchant}/>
        )
    }

    renderContent() {
        if (this.state.selectedMenu === 1) {
            return this.renderHomeContent();
        } else if (this.state.selectedMenu === 3) {
            return this.renderMerchantProfileContent();
        }
    }

    renderBlank() {
        return (
            <div className="container">
                <div className="alert alert-info" role="alert"><strong>提醒：</strong> 正在分析交易数据，请稍后！</div>
            </div>
        );
    }

    renderNoData() {
        return (
            <div className="container">
                <div className="alert alert-warning" role="alert"><strong>提醒：</strong> 店铺当前无交易数据！</div>
            </div>
        );
    }

    render() {
        if (this.state.fetched) {
            return (
                <div>
                    <NavBar menus={this.state.menus} selectedMenu={this.state.selectedMenu} onMenuClick={this.handleMenuClick.bind(this)}/>
                    {this.renderContent()}
                </div>
            );
        } else {
            return this.renderBlank();
        }
    }
}

export default DashboardContainer;
